//
//  MQStatusPictureView.swift
//  MQWeibo
//
//  Created by 毛强 on 16/1/2.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage


private let MQStatusPictureMaxCol:Int = 3
private let itemMargin:CGFloat = 5
private let itemWH:CGFloat = CGFloat(Int((SCREENW - 2 * MQStatusCellMargin - 2 * itemMargin) / CGFloat(MQStatusPictureMaxCol)))

private let MQStatusPictureViewCellId = "MQStatusPictureViewCellId"

class MQStatusPictureView: UICollectionView, UICollectionViewDataSource{
    
    
    var picUrls: [MQStatusPictureInfo]?{
        didSet{
            let count = picUrls?.count ?? 0
            countlLabel.text = "\(count)"
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
               // print(countlLabel)
            }
            
            reloadData()
        }
    }
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var countlLabel:UILabel = {
        let label = UILabel(textColor: UIColor.blackColor(), fontSize: 35)
        return label
    }()
    
    func setupUI(){
        
        dataSource = self
        
        registerClass(MQStatusPictureViewCell.self, forCellWithReuseIdentifier: MQStatusPictureViewCellId)
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
        addSubview(countlLabel)
//        print(countlLabel)
        
        countlLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
    /// 根据图片的张数，计算当前配图视图的大小
    ///
    /// - parameter count: <#count description#>
    ///
    /// - returns: <#return value description#>
    private func calcViewSize(count: Int) -> CGSize {
        // 6 --> 2 行 3列
        // 9 --> 3 行 3列
        
        if count == 1 {
            // 返回那一图片的大小
            // 从缓存里面取出图片 --> key 就是图片地址
            let key = picUrls!.first!.thumbnail_pic
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            // 判断从缓存里面在否真的能够取出图片
            if image != nil {
                var size = image.size
                
                // 过窄的处理
                if size.width < 80 {
                    
                    let width: CGFloat = 80
                    let height = width / size.width * size.height
                    
                    size.width = width
                    // 约束最大的高度
                    size.height = height > 150 ? 150 : height
                }else if size.width > 200 {
                    // 图片过宽的处理
                    let width: CGFloat = 200
                    let height = width / size.width * size.height
                    
                    size.width = width
                    size.height = height
                }
                
                // 更改 cell 的大小
                let layout = collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = size
                
                return size
            }else {
                // 如果没有取出来，直接返回正方形的 size
                return CGSize(width: itemWH, height: itemWH)
            }
        }else{
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSize(width: itemWH, height: itemWH)
        }
        
        
        // 计算列数
        var col = count > MQStatusPictureMaxCol ? MQStatusPictureMaxCol : count
        // 如果是4张图片，显示两列
        if count == 4 {
            col = 2
        }
        // var col = count == 4 ? 2 :（count > HMStatusPictureMaxCol ? HMStatusPictureMaxCol : count）
        
        // 计算行数
        let row = (count - 1) / MQStatusPictureMaxCol + 1
        
        
        // 计算宽度以及高度
        let width = CGFloat(col) * itemWH + CGFloat(col - 1) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat(row - 1) * itemMargin
        
        // 返回结果
        return CGSize(width: width, height: height)
    }}

// MARK: - 数据源方法
extension MQStatusPictureView {
    
    // 返回有多少个 item
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        print(picUrls?.count ?? 0)
        return picUrls?.count ?? 0
        
    }
    
    // 返回每一个 item 对应的 cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(MQStatusPictureViewCellId, forIndexPath: indexPath) as! MQStatusPictureViewCell
        // 设置数据
        cell.picUrl = picUrls![indexPath.item]
        return cell
    }
}


class MQStatusPictureViewCell: UICollectionViewCell{
    // 定义外界设置的属性
    var picUrl: MQStatusPictureInfo? {
        didSet{
            if let urlString = picUrl?.thumbnail_pic {
                let url = NSURL(string: urlString)
                // 显示图片
                imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        // 添加控件
        contentView.addSubview(imageView)
        
        // 添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imageView.contentMode = .ScaleAspectFill
        // 截取掉超出部分
        imageView.clipsToBounds = true
        return imageView
    }()

}
